import WPT from 'wpt';
import { execAppJob } from '../../wptBridge/oldVersion/appBridge';

function loginControl() {
    let options = [];
    let isLoaded = false;

    const showLogin = (reportPosition) => WPT.wptBridge.newAppLogin({
        reportPosition,
        success: () => {
            WPT.loginRefreshUserinfo(() => {
                WPT.userinfo.isSubscribe = 1;
                WPT.loginCallback && WPT.loginCallback();
                options.forEach(item => {
                    item._repeatAjax ? item._repeatAjax() : $.ajax(item);
                });
                options = [];
                isLoaded = false;
            }, options);
        },
        fail: () => {
            options = [];
            isLoaded = false;
        },
    });

    function login(option) {
        if (option) {
            options.push(option);
        }
        if (!isLoaded) {
            WPT.showLogin
                ? showLogin(
                    option?._ereportLoginPosition
                        || option?.data?._ereportLoginPosition
                        || option?.url
                        || ''
                )
                : execAppJob(showLogin);
            isLoaded = true;
        }
    }
    return login;
}

WPT.showLogin = WPT.showLogin || function () {};

const AppLogin = loginControl();

export { AppLogin };
